package com.ruoyi.web.controller.system;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.system.dto.UpdateInviteCodeDTO;
import com.ruoyi.web.controller.system.dto.UpdatePwdDTO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.User;
import com.ruoyi.system.service.IUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/h5/user")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;

    /**
     * 查询用户列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserListWithInviter(user);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @Anonymous
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userService.selectUserById(id));
    }

    /**
     * 新增用户
     */
    @Anonymous
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user)
    {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Anonymous
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Anonymous
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 根据手机号查询用户
     */
    @Anonymous
    @GetMapping("/mobile/{mobile}")
    public AjaxResult getInfoByMobile(@PathVariable("mobile") String mobile)
    {
        return success(userService.selectUserByMobile(mobile));
    }

    /**
     * 根据邀请码查询用户
     */
    @Anonymous
    @GetMapping("/invite/{inviteCode}")
    public AjaxResult getInfoByInviteCode(@PathVariable("inviteCode") String inviteCode)
    {
        return success(userService.selectUserByInviteCode(inviteCode));
    }






    public String generateInviteCode() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder inviteCode = new StringBuilder();

        // 生成8位邀请码
        for (int i = 0; i < 8; i++) {
            inviteCode.append(chars.charAt(random.nextInt(chars.length())));
        }

        boolean b = userService.checkInviteCodeExists(inviteCode.toString());
        if (b) {
            // 如果已存在，递归生成新的邀请码
            return generateInviteCode();
        }

        return inviteCode.toString();
    }

    /**
     * 修改用户邀请码
     */
    @Anonymous
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/updateInviteCode")
    public AjaxResult updateInviteCode(@Validated @RequestBody UpdateInviteCodeDTO dto)
    {
        User user = new User();
        user.setId(dto.getUserId());
        if (StringUtils.isNotEmpty(dto.getInviteCode()) && userService.checkInviteCodeExists(dto.getInviteCode()))
        {
            return error("邀请码已存在");
        }
        if (StringUtils.isEmpty(dto.getInviteCode())){
            user.setInviteCode(generateInviteCode());
        }else {
            user.setInviteCode(dto.getInviteCode());
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserInviteCode(user));
    }

    @Anonymous
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePwd")
    public AjaxResult resetPassword(@Validated @RequestBody UpdatePwdDTO dto) {
        // 查询用户
        User user = userService.selectUserByMobile(dto.getMobile());
        if (user == null) {
            return error("用户不存在");
        }

        // 更新密码
        user.setPassword(encryptPassword(dto.getPassword()));
        user.setUpdateTime(new Date());
        user.setUpdateBy(getUsername());

        int rows = userService.updateUser(user);
        if (rows > 0) {
            return success("密码修改成功");
        }
        return error("密码修改失败");
    }

    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
    }
} 